﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="../themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../demo.css">
    <script type="text/javascript" src="../jquery.min.js"></script>
    <script type="text/javascript" src="../jquery.cookie.js"></script>
    <script type="text/javascript" src="../jquery.easyui.min.js"></script>
	<script type="text/javascript" src="../locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="../extend.js"></script>
    <script>
        var dataListCache = null;
        var dataCache = null;
        var orderTypes = getOrderType();
        var salesPoints =getSalesPoint();
        var employees = getEmployee();
        var customers =getCustomer();
        var productions =getProduction();
        var unitGroups=getUnitGroup();
        var inndesigner = getInnDesigner(employees);
        var outdesigner = getOutDesigner(employees);
        var blands=getBland();
        var series = getSeries();
        var units = getUnit();
        var quotes = dataFetcher("../../api/quote/list");
        var appId = GetQueryString("moduleid");
        var rowEditing = -1;
        var fieldEditing = -1;
        var columnsList = [];
        var editing = false;
        var searchArg = [];
        document.onkeydown = keyDown;
        window.onresize = calSize;
        $(document).ready(function () {
			initBase();
            setData();
            calSize();
            getColumnVisable();
        });

        
        function getColumnVisable(){
            var allColumn = $('#orderDetailList').datagrid('getColumnFields');
            for(var j=0;j<allColumn.length;j++){
                var col=$('#orderDetailList').datagrid('getColumnOption',allColumn[j]);
                if(!(col.hidden)&&(col.editor!=undefined)){
                    columnsList.push(allColumn[j]);
        		}
            }
        }
        function initBase() {
            $('#OrderType').combobox({ data: orderTypes });
			$('#SalesPointId').combogrid(getComboGridInfo('门店','Name',[[
                                        {field:'AutoId',title:'ID',width:80},
                                        {field:'Code',title:'代号',width:120},
                                        {field:'Name',title:'名称',width:150,align:'right'},
                                    ]],salesPoints,dataRebinding));
        }
		function dataRebinding(n,o){
			var emps = [];
			var empsid = [];
            var empsWithVIP = getSalesVIP(employees);
			var cuss=[];
			$.ajaxSettings.async=false;
			$.get('../../api/salespoint/listemployees?spid='+n,function(data){
				if(data.Result==0){
					var r = JSON.parse(data.Data);
					for(var j=0;j<r.length;j++){
						for(var i=0;i<employees.length;i++){
							if(employees[i].AutoId == r[j].EmployeeId){
								emps.push(employees[i]);
                                empsWithVIP.push(employees[i]);
							}
						}
					}
                    $('#SecSalesId').combobox({ data: emps });
                    $('#SalesId').combobox({ data: empsWithVIP });
				}
			},'json');
			for(var i=0;i<customers.length;i++){
				if(customers[i].SalesPointId == n){
					cuss.push(customers[i]);
				}
			}
			$('#CustomerId').combogrid(getComboGridInfo('客户','Name',[[
                                        {field:'AutoId',title:'ID',width:80},
                                        {field:'Code',title:'代号',width:120},
                                        {field:'Tel',title:'电话',width:120},
                                        {field:'Name',title:'名称',width:150,align:'right'},
                                    ]],cuss));
			$.ajaxSettings.async=true;
		}
		function pageChanging(pageNumber, pageSize) {
            showMask("查找中");
			var customerid = GetQueryString("customerid");
			if(customerid!=null){
				searchArg.push({'Key':'CustomerId','Op':'Eq','Value':customerid});
			}
			var autoid = GetQueryString("autoid");
			if(autoid!=null){
				searchArg.push({'Key':'autoid','Op':'Eq','Value':autoid});
			}
            $.get('../../api/order/list', { Args: searchArg, Length: pageSize, Pos: (pageNumber-1) * pageSize }, function (data) {
                if (data.Result == 0) {
                    dataListCache = JSON.parse(data.Data);
                    $("#orderList").datagrid("loadData", dataListCache);
                    $("#orderList").datagrid('getPager').pagination({ total: data.Count, pageNumber: pageNumber, onSelectPage: pageChanging });
                } else {
                    $.messager.alert('提示', data.Message, 'error');
                }
                hideMask();
            }, 'json');
        }
        function setData() {
            pageChanging(1,10);
        }
        window.onresize = calSize;
        function calSize(){
            var height=window.parent.document.getElementById("mainFrame").clientHeight;
            var width=window.parent.document.getElementById("mainFrame").clientWidth;
            window.parent.document.getElementById(appId).height = height-32;
            $("#orderList").datagrid('resize',{height:height-76,width:width-15});
            $("#toolbar").panel({width:width-15});
            $("#editToolbar").panel({width:width-15});
            $("#detailEditToolBar").panel({width:width-15});
            
            //$("#editZone").panel('resize',{height:height-76,width:width-15});
            $("#editZone").panel('resize',{width:width-15,height:248});
            if(hideMain){
                $("#orderDetailList").datagrid('resize',{width:width-15,height:height-148});
            }else{
                $("#orderDetailList").datagrid('resize',{width:width-15,height:height-366});
            }
        }
        function setCellEditable(){
            $('#orderDetailList').datagrid('validateRow', rowEditing);
            $('#orderDetailList').datagrid('endEdit', rowEditing);
            $('#orderDetailList').datagrid('selectRow', rowEditing).datagrid('editCell', {index: rowEditing,field: fieldEditing});
        }
        var hideMain = false;
        function keyDown(event) {
            var s_key=window.event.keyCode;
            if((s_key==90)&&(event.ctrlKey)){
                if(!hideMain){
                    hideMain = true;
                    $("#editZone").panel('close');
                }else{
                    hideMain = false;
                    $("#editZone").panel('open');
                }
                calSize();
            }
            if(!editing){
                return;
            }
            var e = event || window.event;
            var keyCode = e.keyCode || e.which;
            switch (keyCode) {
                case 37:
                    hMove(-1);
                    break;
                case 39:
                    hMove(1);
                    break;
            }
        }
        function hMove(direction){
            if(rowEditing==-1){
                return;
            }
            if(fieldEditing==-1){
                fieldEditing = columnsList[0];
            }
            var ed=$('#orderDetailList').datagrid('getEditor', {index:rowEditing,field:fieldEditing});
            if(!ed){
                return;
            }
            if(direction>=0){
                direction=1;
            }
            else{
                direction=-1;
            }
            var tag = null;
            if($(ed.target).data('textbox')){
                tag = $(ed.target).textbox('textbox')[0];
            }
            var valueLenth=tag.value.length;
            if(tag==null||tag.readOnly||(tag.selectionStart==0 || tag.selectionStart==undefined)&&direction<0
                ||(tag.selectionEnd==valueLenth || tag.selectionEnd==undefined)&&direction>=0){
                for(var i=0;i<columnsList.length;i++){
                    if(fieldEditing==columnsList[i] && (i+direction)>=0 && (i+direction)<columnsList.length){
                        fieldEditing=columnsList[(i+direction)];
                        break;
                    }
                }
                setCellEditable();
            }
            
        }
        function initVal() {
            $('#AutoId').val(dataCache.AutoId);
            $('#Flag').val(dataCache.Flag);
			$('#State').val(dataCache.State);
            $('#Site').val(dataCache.Site);
			$('#SalesPointId').combogrid("setValue", dataCache.SalesPointId);
            $('#OrderType').combobox("setValue", dataCache.OrderType);
            $('#OrderCode').textbox("setValue", dataCache.OrderCode);
            $('#SalesId').combobox("setValue", dataCache.SalesId);
            $('#SecSalesId').combobox("setValue", dataCache.SecSalesId);
            $('#DeliveryDate').datebox("setValue", dataCache.DeliveryDate);
			$('#DesignerId').combobox("setValue", dataCache.DesignerId);
            $('#SalesDate').datebox("setValue", dataCache.SalesDate);
            $('#CustomerId').combogrid("setValue", dataCache.CustomerId);
            $('#CustomerName').textbox("setValue", dataCache.CustomerName);
            $('#Tel').textbox("setValue", dataCache.Tel);
            $('#DeliveryAddress').textbox("setValue", dataCache.DeliveryAddress);
            $('#Note').textbox("setValue", dataCache.Note);
            $('#OrderDiscount').numberbox("setValue", dataCache.OrderDiscount);
            //$('#DepartmentId').combobox("setValue", dataCache.DepartmentId);
            $('#Total').numberbox("setValue", dataCache.Total);
            $('#StateNote').textbox("setValue",valToName(docState,dataCache.State));
            if(dataCache.State==3||dataCache.State==4){
                $('#approveIcon').show();
            }else{
                $('#approveIcon').hide();
            }
			resetTable();
        }
        function createNewRecord() {
			$('#approveIcon').hide();
            dataCache = new Object();
			dataCache.OrderType = orderTypes[0].AutoId;
            var profile = JSON.parse( $.cookie('profile'));
            dataCache.SalesId = profile.EmployeeId;
            dataCache.SalesPointId = profile.SalesPoint;
            dataCache.SalesDate = new Date().toLocaleDateString();
            dataCache.OrderCode = getAutoCode('SAM_ORDER_SET');
            initVal();
			updateBtnState(0,true);
            $('#editContent').window('open');
        }
        function editRecord(rowIndex, rowData) {
			updateBtnState(rowData.State,true);
            dataCache = rowData;
            initVal();
            $('#editContent').window('open');
        }
        function submitChange() {
            if (dataCache == null) {
                $.messager.alert("错误", "无法获取被编辑的对象", "error");
                return;
            }
			var oldData = JSON.parse(JSON.stringify(dataCache));
            showMask();
            dataCache.Flag = $("#Flag").val();
			dataCache.State = $("#State").val();
            dataCache.OrderType = $('#OrderType').combobox("getValue");
            dataCache.OrderCode = $('#OrderCode').textbox("getValue");
            dataCache.SalesId = $('#SalesId').combobox("getValue");
			dataCache.DesignerId = $('#DesignerId').combobox("getValue");
            dataCache.SalesDate = $('#SalesDate').datebox("getValue");
            dataCache.CustomerId = $('#CustomerId').combogrid("getValue");
            dataCache.CustomerName = $('#CustomerName').textbox("getValue");
            dataCache.Tel = $('#Tel').textbox("getValue");
            dataCache.Note = $('#Note').textbox("getValue");
            dataCache.DeliveryAddress = $('#DeliveryAddress').textbox("getValue");
            dataCache.SalesPointId = $('#SalesPointId').combogrid("getValue");
			dataCache.OrderDiscount = $('#OrderDiscount').numberbox("getValue");
            dataCache.SecSalesId = $('#SecSalesId').combobox("getValue");
            dataCache.DeliveryDate = $('#DeliveryDate').datebox("getValue");
            var rows = $('#orderDetailList').datagrid('getAllRows');
            var total = 0;
            for (var i = 0; i < rows.length; i++) {
                total = total + rows[i].Amount;
            }
            dataCache.Total = total;
            //dataCache.DepartmentId = $('#DepartmentId').combobox("getValue");
            $.post("../../api/order/set", dataCache, function (response) {
                if (response.Result == 0) {
                    dataCache = JSON.parse(response.Data);
					$('#Flag').val(dataCache.Flag);
					$('#AutoId').val(dataCache.AutoId);
                    if(dataCache.Flag!=1){
                        for(var i=0;i<dataListCache.length;i++){
                            if(dataListCache[i].AutoId == dataCache.AutoId){
                                dataListCache.splice(i,1,dataCache);
								console.log('列表第'+i+'项被更新');
                                break;
                            }
                        }
                    }else{
						dataListCache.splice(0,0,dataCache);
						console.log('新项被追加到列表');
					}
                    submitDetail(
						function(){$('#orderList').datagrid('loadData', dataListCache);$('#orderList').datagrid('selectRecord', dataCache.AutoId); $('#editContent').window('close');},
						function(msg){$.messager.alert("信息", msg, "info");},
						function(){$.messager.alert("信息", '系统内部错误', "info");}
					);
                    updateBtnState(dataCache.State,true);
                } else {
                    $.messager.alert("错误", response.Message, "error");
					dataCache = oldData;
                }
            })
                .error(function () {
                    $.messager.alert("错误", "系统内部错误", "error");
					dataCache = oldData;
                })
                .complete(function () {
                    hideMask();
                });
        }
        function boolFormatter(value, row, index) {
            if (value) {
                return "是";
            } else {
                return "否";
            }
        }
        function customerFormatter(value, row, index) {
            return valToName(customers, value);
        }
        function salesPointFormatter(value, row, index) {
            return valToName(salesPoints, value);
        }
        function salesFormatter(value, row, index) {
            return valToName(employees, value);
        }
        function orderTypeFormatter(value, row, index) {
            return valToName(orderTypes, value);
        }
        function loadDataCache(rowIndex, rowData) {
			console.log(JSON.stringify(rowData));
            dataCache = rowData;
			updateBtnState(dataCache.State,true);
        }
        function addItem() {
            if (editing) {
                $('#orderDetailList').datagrid('insertRow',{index:rowEditing+1,row:{AutoId:0,Flag:0}});

            } else {
                $.messager.alert("消息", "先按编辑键进入编辑状态", "info");
            }
        }
		function removeItem(){
			if(rowEditing!=-1){
				$('#orderDetailList').datagrid('cancelEdit', rowEditing).datagrid('deleteRow',rowEditing);
			}else{
				$.messager.alert('提示','需要整行选中才能删除');
			}
        }
        function editTable() {
            if (!editing) {
                $('#orderDetailList').datagrid("enableCellEditing");
                editing = true;
                $('#detailAdd').linkbutton("enable");
                $('#detailDel').linkbutton("enable");
                $('#detailSave').linkbutton("enable");
                $('#detailCancel').linkbutton("enable");
                $('#detailEdit').linkbutton("disable");
            } else {
                $.messager.alert("消息", "当前正在编辑中", "info");
            }
        }
        function setRowIndex(index, row) {
            rowEditing = index;
        }
        function endEditTable() {
            $('#orderDetailList').datagrid('endEdit', rowEditing);
            $('#orderDetailList').datagrid("disableCellEditing");
            rowEditing = -1;
            fieldEditing = -1;
            editing = false;
            $('#detailAdd').linkbutton("disable");
            $('#detailDel').linkbutton("disable");
            $('#detailSave').linkbutton("disable");
            $('#detailCancel').linkbutton("disable");
            $('#detailEdit').linkbutton("enable");
        }
        function setEditingLocation(index, field){
            if(!editing){
                return;
            }
            var editor = $('#orderDetailList').datagrid('getEditor', { index: index, field: field });
            if(editor!=null){
                rowEditing=index;
                fieldEditing=field;
            }
        }
        function resetTable() {
			listDetail(dataCache.AutoId);
            endEditTable();
        }
        function listDetail(orderId) {
            if (orderId == 0||orderId==undefined) {
                $('#orderDetailList').datagrid("loadData", []).datagrid('clientPaging'); 
                return;
            }
			$('#orderDetailList').datagrid("loading");
            $.get("../../api/order/listdetails?orderid=" + orderId, function (data) {
                if (data.Result == 0) {
                    var detail = JSON.parse(data.Data);
                    $('#orderDetailList').datagrid("loadData", detail).datagrid('clientPaging');
                }
            }, "json")
                .error(function () {
                    $.messager.alert("错误", "系统内部错误", "error");
                })
                .complete(function () {
					$('#orderDetailList').datagrid("loaded");
                });
        }
        function setProduction(index, row) {
            if (editing) {
                var edProduction = $('#orderDetailList').datagrid('getEditor', { index: index, field: 'ProductionId' });
                if (edProduction != null) {
					var options = getComboGridInfo(null,'Name',[[
									{field:'AutoId',title:'ID',width:60},
									{field:'Code',title:'代号',width:60},
									{field:'SearchCode',title:'搜索码',width:60},
									{field:'Name',title:'名称',width:100}
								]],productions);
					options.onChange = productionSelected;			
                    $(edProduction.target).combogrid(options);
                }
            }
        }
        function submitDetail(succFunc,unSuccFunc,faultFunc) {
            if (rowEditing != -1) {
                var valid = $('#orderDetailList').datagrid('validateRow', rowEditing);
                if (!valid) {
					unSuccFunc("错误的数据格式");
                    //$.messager.alert("错误", "错误的数据格式", "error");
                    //return;
                }
                $('#orderDetailList').datagrid('endEdit', rowEditing);
            }
            else {
                endEditTable();
            }
            var data = $('#orderDetailList').datagrid('getAllRows');
            $.post("../../api/order/setdetails", { MasterId: dataCache.AutoId, Data: data }, function (response) {
                if (response.Result == 0) {
                    dataCache.Modules = JSON.parse(response.Data);
					succFunc();
                } else {
					unSuccFunc(response.Message);
                    //$.messager.alert("错误", response.Message, "error");
                }
            })
                .error(function () {
					faultFunc();
                })
                .complete(function () {
                    endEditTable();
                });
        }
        function productionFormatter(value, row, index) {
            return valToName(productions, value);
        }
        function unitGroupFormatter(value, row, index) {
            return valToName(unitGroups, value);
        }      
        function unitFormatter(value, row, index) {
            return valToName(units, value);
        }        
        function seriesFormatter(value, row, index) {
            return valToName(series, value);
        }        
        function blandFormatter(value, row, index) {
            return valToName(blands, value);
        }
        function productionSelected(n,o){
            for(var i=0;i<productions.length;i++){
                if(productions[i].AutoId==n){
                    var row =$('#orderDetailList').datagrid('getSelected');
                    row.ProductionName=productions[i].Name;
                    row.Specification=productions[i].Specification;
                    row.UnitGroupId=productions[i].UnitGroupId;
                    row.UnitId=productions[i].UnitId;
                    row.SalesUnitId=productions[i].SalesUnitId;
                    row.Free=productions[i].Free;
                    row.Promotion=productions[i].Promotion;
                    row.BlandId=productions[i].BlandId;
                    row.SeriesId=productions[i].SeriesId;
					row.ProductionTypeId = productions[i].ProductionTypeId;
                    row.Rate = productions[i].Rate;
                    $.get("../../api/quote/getbyproduction?productionid="+n,
                        function(data){
                            if(data.Result == 0){
                                var quote = JSON.parse(data.Data);
                                row.Price = quote.PriceLv2;
                                row.QuoteId = quote.QuoteId;
                                row.PriceRef0 = quote.PriceLv0;
                                row.PriceRef1 = quote.PriceLv1;
								row.PriceRef2 = quote.PriceLv2;
                                row.PriceRef3 = quote.PriceLv3;
                                row.PriceRef4 = quote.PriceLv4;
                                row.PriceRef5 = quote.PriceLv5;
                                row.Discount = quote.PriceLv2/quote.PriceLv0;
                            }
                            else{
                            }
                        },"json") 
                        .error(function () {
                                $.messager.alert("错误", "系统内部错误", "error");
                        })
                        .complete(function () {
                        });
                }
            }
        }
        function quoteNameFormatter(value, row, index){
            return valToName(quotes,value);
        }
        function qtyUpdated(n,o){
			$('#OrderDiscount').numberbox('setValue',0);
            var row =$('#orderDetailList').datagrid('getSelected');
            row.Amount = n * row.Price;
            row.DisAmount = row.PriceRef2 * row.Quantity1 * (1 - row.Discount);
            row.Quantity2 = row.Rate*n;
            row.Define6 = row.PriceRef0*n; 
			recalTotal();
        }
        function freeUpdated(n, o) {
            var row = $('#orderDetailList').datagrid('getSelected');
            if (n) {
                row.Price = 0;
            } else {
                row.Price = row.PriceRef2;
            }
            priceUpdated(row.Price, 0);

        }
        function priceUpdated(n,o){
			$('#OrderDiscount').numberbox('setValue',0);
            var row =$('#orderDetailList').datagrid('getSelected');
            row.Amount = row.Quantity1*n;
            if(row.PriceRef0>0){
                row.Discount = n/row.PriceRef0;
            }else{
                row.Discount = 0;
            }
            row.DisAmount = row.PriceRef2 * row.Quantity1 * (1 - row.Discount);
			recalTotal();
        }
		function totalChange(n,o){
			var rows = $('#orderDetailList').datagrid('getAllRows');
			var stdPrice = 0;
            if(!rows||rows.length==0){
                return;
            }
            
			for(var i=0;i<rows.length;i++){
				if(!rows[i].Quantity1||!rows[i].PriceRef2){
					return;
				}
				stdPrice = rows[i].Quantity1 * rows[i].PriceRef2+stdPrice;
			}
			console.log(stdPrice);
			var priceDiscount = n;
			var rate = (stdPrice-priceDiscount)/stdPrice;
			console.log("整单折扣率为"+rate);
			for(var i=0;i<rows.length;i++){
				rows[i].Price = rows[i].Price * rate;
				rows[i].Amount = rows[i].Amount*rate;
				rows[i].Discount = rows[i].Price/rows[i].PriceRef0;
				rows[i].DisAmount = rows[i].DisAmount+n;
				$('#orderDetailList').datagrid('refreshRow',i);
			}
			recalTotal();
			//$('#orderDetailList').datagrid('reload');
		}
		function recalTotal(){
			var total = 0;
			var rows =  $('#orderDetailList').datagrid('getAllRows');
			for(var i=0;i<rows.length;i++){
				total = rows[i].Amount +total;
			}
			$('#Total').numberbox('setValue',total);
		}
		function deleteRecord(){
			if (dataCache == null||dataCache.AutoId==0) {
                $.messager.alert("错误", "请先选中要删除的对象", "error");
                return;
            }
			$.messager.confirm('删除提示', '确定删除该记录?', function(r){
				if (r){
					showMask();
					$.get("../../api/order/removewithdetail?id="+dataCache.AutoId,function(response){
						if(response.Result==0){
							for(var i=0;i<dataListCache.length;i++){
								if(dataListCache[i].AutoId == dataCache.AutoId){
									dataListCache.splice(i,1);
									break;
								}
							}					
							dataCache = null;
							$('#orderList').datagrid('loadData', dataListCache); 
							$.messager.alert("信息","操作成功","info");
						}else{
							$.messager.alert("错误",response.Message,"error");
						}
					})
					.error(function(){
						$.messager.alert("错误","系统内部错误","error");
					})
					.complete(function() { 
						hideMask();
					});	
				}
			});		
		}
		function submitRecord(){
			showMask();
			$.get("../../api/order/submit?id="+dataCache.AutoId,function(response){
				if(response.Result==0){
					for(var i=0;i<dataListCache.length;i++){
						if(dataListCache[i].AutoId == dataCache.AutoId){
							dataListCache[i].State = 2;
							break;
						}
					}					
					$('#orderList').datagrid('loadData', dataListCache); 
                    updateBtnState(dataCache.State,true);
                    $('#StateNote').textbox('setValue',valToName(docState,dataCache.State));
					$.messager.alert("信息","操作成功","info");
					}else{
						$.messager.alert("错误",response.Message,"error");
					}
				})
				.error(function(){
					$.messager.alert("错误","系统内部错误","error");
				})
				.complete(function() { 
					hideMask();
				});	
		}
		function recallRecord(){
			showMask();
			$.get("../../api/order/recall?id="+dataCache.AutoId,function(response){
				if(response.Result==0){
					for(var i=0;i<dataListCache.length;i++){
						if(dataListCache[i].AutoId == dataCache.AutoId){
							dataListCache[i].State = 1;
							break;
						}
					}					
					$('#orderList').datagrid('loadData', dataListCache); 
                    updateBtnState(dataCache.State,true);
                    $('#StateNote').textbox('setValue',valToName(docState,dataCache.State));
					$.messager.alert("信息","操作成功","info");
					}else{
						$.messager.alert("错误",response.Message,"error");
					}
				})
				.error(function(){
					$.messager.alert("错误","系统内部错误","error");
				})
				.complete(function() { 
					hideMask();
				});	
			
		}
		function approveRecord(){
			showMask();
			$.get("../../api/order/approve?id="+dataCache.AutoId,function(response){
				if(response.Result==0){
					for(var i=0;i<dataListCache.length;i++){
						if(dataListCache[i].AutoId == dataCache.AutoId){
							dataListCache[i].State = 3;
							break;
						}
					}					
					$('#orderList').datagrid('loadData', dataListCache); 
                    updateBtnState(dataCache.State,true);
                    $('#StateNote').textbox('setValue',valToName(docState,dataCache.State));
                    $('#approveIcon').show();
					$.messager.alert("信息","操作成功","info");
					}else{
						$.messager.alert("错误",response.Message,"error");
					}
				})
				.error(function(){
					$.messager.alert("错误","系统内部错误","error");
				})
				.complete(function() { 
					hideMask();
				});	
			
		}
		function revertRecord(){
			showMask();
			$.get("../../api/order/revert?id="+dataCache.AutoId,function(response){
				if(response.Result==0){
					for(var i=0;i<dataListCache.length;i++){
						if(dataListCache[i].AutoId == dataCache.AutoId){
							dataListCache[i].State = 1;
							break;
						}
					}					
					$('#orderList').datagrid('loadData', dataListCache); 
                    updateBtnState(dataCache.State,true);
                    $('#StateNote').textbox('setValue',valToName(docState,dataCache.State));
                    $('#approveIcon').hide();
					$.messager.alert("信息","操作成功","info");
					}else{
						$.messager.alert("错误",response.Message,"error");
					}
				})
				.error(function(){
					$.messager.alert("错误","系统内部错误","error");
				})
				.complete(function() { 
					hideMask();
				});	
			
		}
        function rejectRecord() {
            showMask();
            $.get("../../api/order/reject?id=" + dataCache.AutoId, function (response) {
                if (response.Result == 0) {
                    for (var i = 0; i < dataListCache.length; i++) {
                        if (dataListCache[i].AutoId == dataCache.AutoId) {
                            dataListCache[i].State = 1;
                            break;
                        }
                    }
                    $('#orderList').datagrid('loadData', dataListCache);
                    updateBtnState(dataCache.State, true);
                    $('#StateNote').textbox('setValue', valToName(docState, dataCache.State));
                    $.messager.alert("信息", "操作成功", "info");
                } else {
                    $.messager.alert("错误", response.Message, "error");
                }
            })
            .error(function () {
                $.messager.alert("错误", "系统内部错误", "error");
            })
            .complete(function () {
                hideMask();
            });
        }

    </script>
    </head>
        <body onload = "hideMask()">
            <script>showMask('正在载入数据');</script>
            <div id="toolbar" class="easyui-panel" style="padding:1px;">
				<a href="#" id="btnCreate" class="easyui-linkbutton" data-options="onClick:createNewRecord,iconCls:'icon-edit',plain:true">新建</a>
				<a href="#" id="btnDelete" class="easyui-linkbutton" data-options="onClick:deleteRecord, iconCls:'icon-remove',plain:true">删除</a>
				<a href="#" id="btnSearch" class="easyui-linkbutton" data-options="onClick:function(){$('#search').window('open')},iconCls:'icon-search',plain:true">搜索</a>
				<a href="#" id="btnSubmit" class="easyui-linkbutton" data-options="onClick:submitRecord,iconCls:'icon-redo',plain:true,disabled:true">提审</a>
				<a href="#" id="btnRecall" class="easyui-linkbutton" data-options="onClick:recallRecord,iconCls:'icon-undo',plain:true,disabled:true">撤回</a>
				<a href="#" id="btnApprove" class="easyui-linkbutton" data-options="onClick:approveRecord,iconCls:'icon-ok',plain:true,disabled:true">审核</a>
				<a href="#" id="btnRevert" class="easyui-linkbutton" data-options="onClick:revertRecord,iconCls:'icon-cancel',plain:true,disabled:true">反审</a>
				<a href="#" id="btnReject" class="easyui-linkbutton" data-options="onClick:rejectRecord,iconCls:'icon-clear',plain:true,disabled:true">退回</a>
				<a href="#" id="btnExp" class="easyui-linkbutton" data-options="onClick:function(){exportData('../../api/order/export',searchArg)} ,iconCls:'icon-pencil',plain:true">导出</a>
            </div>
            <div style="margin:2px"></div>
            <table id="orderList" class="easyui-datagrid"
                   data-options="pagination:true,rownumbers: true,singleSelect:true,method:'get',onDblClickRow:editRecord,onClickRow:loadDataCache,pagination:true,rownumbers:true,striped:true,idField:'AutoId'">
                <thead>
                    <tr>
                        <th data-options="field:'AutoId',hidden:true"></th>
                        <th data-options="field:'Flag',hidden:true"></th>
                        <th data-options="field:'OrderType',width:120,align:'right',formatter:orderTypeFormatter">单据类型</th>
                        <th data-options="field:'OrderCode',width:140,align:'right'">单号</th>
                        <th data-options="field:'SalesId',width:120,align:'right',formatter:salesFormatter">业务员</th>
                        <th data-options="field:'SalesDate',width:120,align:'right'">销售日期</th>
                        <th data-options="field:'CustomerId',hidden:true ,width:120,align:'right',formatter:customerFormatter">客户</th>
                        <th data-options="field:'CustomerName',width:120,align:'right'">客户名称</th>
                        <th data-options="field:'SecSalesId',width:120,align:'right',formatter:salesFormatter">导购</th>
                        <th data-options="field:'Tel',width:120,align:'right'">联系电话</th>
                        <th data-options="field:'DeliveryAddress' ,hidden:true,width:120,align:'right'">送货地点</th>
                        <th data-options="field:'Note' ,hidden:true,width:120,align:'right'">备注</th>
                        <th data-options="field:'SalesPointId',width:120,align:'right',formatter:salesPointFormatter">门店</th>
                        <th data-options="field:'Status' ,hidden:true,width:120,align:'right'">状态</th>
                        <th data-options="field:'Total',width:120,align:'right',formatter:moneyFormatter">总价</th>
                        <th data-options="field:'OrderDiscount',width:120,align:'right'">整单折扣</th>
                        <th data-options="field:'Currency' ,hidden:true,width:120,align:'right'">币种</th>
                        <th data-options="field:'State',width:100,formatter:stateFormatter">状态</th>
                    </tr>
                </thead>
            </table>
            <div id="editContent" class="easyui-window" title="编辑框" data-options="noheader:true,maximized:true,modal:true,closed:true,iconCls:'icon-save',border:false" style="padding:5px 5px 0px 5px">
                <div class="easyui-panel" id="editToolbar" style="padding:1px;width:100%">
                    <a href="#" class="easyui-linkbutton" data-options="onClick:submitChange,iconCls:'icon-save',plain:true">保存</a>
                    <a href="#" class="easyui-linkbutton" data-options="onClick:initVal,iconCls:'icon-no',plain:true">取消</a>
					<a href="#" id="_btnSubmit" class="easyui-linkbutton" data-options="onClick:submitRecord,iconCls:'icon-redo',plain:true,disabled:true">提审</a>
					<a href="#" id="_btnRecall" class="easyui-linkbutton" data-options="onClick:recallRecord,iconCls:'icon-undo',plain:true,disabled:true">撤回</a>
					<a href="#" id="_btnApprove" class="easyui-linkbutton" data-options="onClick:approveRecord,iconCls:'icon-ok',plain:true,disabled:true">审核</a>
					<a href="#" id="_btnRevert" class="easyui-linkbutton" data-options="onClick:revertRecord,iconCls:'icon-cancel',plain:true,disabled:true">反审</a>
					<a href="#" id="_btnReject" class="easyui-linkbutton" data-options="onClick:rejectRecord,iconCls:'icon-clear',plain:true,disabled:true">退回</a>
                    <a href="#" class="easyui-linkbutton" data-options="onClick:function(){$('#editContent').window('close');},iconCls:'icon-blank',plain:true">关闭</a>
                </div>
                <div style="margin:2px"></div>
                <div id="editZone" class="easyui-panel" style="padding:4px 4px 0px 4px" >
                    <table>
                        <tr>
                            <td><input class="easyui-combobox" id="OrderType" style="width:300px" data-options="label:'单据类型:',valueField: 'AutoId',textField: 'Name',required:true"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-textbox" id="OrderCode" style="width:300px" data-options="label:'类型单号:',required:true"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-combobox" id="SalesId" style="width:300px" data-options="label:'业务员:',valueField: 'AutoId',textField: 'Name',required:true,data:getSalesVIP(employees)"></td>
                        </tr>
                        <tr>
                            <td><input class="easyui-datebox" id="SalesDate" style="width:300px" data-options="label:'销售日期:',formatter:dateFormatter,parser:dateParser"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-combogrid" id="SalesPointId" style="width:300px"></td>
                            <td>&nbsp;</td>
                            <td>
                                <input class="easyui-combogrid" id="CustomerId" style="width:300px" data-options="label:'客户',
                                    onChange:function(n,o){
                                       for(var i=0;i<customers.length;i++){
                                            if(customers[i].AutoId==n){
                                                $('#CustomerName').textbox('setValue',customers[i].Name);
                                                $('#Tel').textbox('setValue', customers[i].Tel);
                                                $('#DeliveryAddress').textbox('setValue', customers[i].DeliveryAddress);
                                                $('#SecSalesId').combobox('setValue', customers[i].SecSalesId);
                                                $('#DesignerId').combobox('setValue', customers[i].DesignerId);
                                                $('#CustomerSource').combobox('setValue', customers[i].Source);
                                            }
                                        }
                                    }">
                            </td>
                        </tr>
                        <tr>
                            <td><input class="easyui-combobox" id="SecDesignerId" style="width:300px" data-options="label:'驻店设计师:',valueField: 'AutoId',textField: 'Name',data:inndesigner"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-textbox" id="Tel" style="width:300px" data-options="label:'联系电话:'"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-numberbox" id="Total" style="width:300px" data-options="label:'总金额:',editable:false,precision:2,groupSeparator:',',decimalSeparator:'.',prefix:'￥'"></td>
                        </tr>
                        <tr>
                            <td><input class="easyui-combobox" id="DesignerId" style="width:300px" data-options="label:'家装设计师:',data:outdesigner, valueField: 'AutoId',textField: 'Name'"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-numberbox" id="OrderDiscount" style="width:300px" data-options="label:'折扣金额:',onChange:totalChange,precision:2,groupSeparator:',',decimalSeparator:'.',prefix:'￥'"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-textbox" id="StateNote" style="width:300px" data-options="label:'状态:',editable:false"></td>
                        </tr>
                        <tr>
                            <td><input class="easyui-combobox" id="CustomerSource" style="width:300px" data-options="label:'客户来源:',valueField: 'AutoId',textField: 'Name',data:customerSourceData"></td>
                            <td>&nbsp;</td>
                            <td><input class="easyui-combobox" id="SecSalesId" style="width:300px" data-options="label:'导购:',valueField: 'AutoId',textField: 'Name',required:true"></td>
                            <td>&nbsp;</td>    
                            <td><input class="easyui-datebox" id="DeliveryDate" style="width:300px" data-options="label:'送货日期:',required:true"></td>
                        </tr>
                        <tr>
                            <td colspan="5"><input class="easyui-textbox" id="DeliveryAddress" style="width:800px" data-options="label:'送货地址:'"></td>
                        </tr>
                        <tr>
                            <td colspan="5"><input class="easyui-textbox" id="Note" style="width:800px" data-options="label:'备注:'"></td>
                        </tr>
                    </table>
					<div id='approveIcon' hidden=true style="z-index:999;position: absolute;top: 50px;right: 50px;width: 216px;height:157px;background: url(../image/approved.png)"></div>
                    <div hidden>
                        <p id="AutoId"></p>
                        <p id="Flag"></p>
                        <p id="Site"></p>
						<p id="State"></p>
						<input class="easyui-textbox" id="CustomerName" style="width:300px" data-options="label:'客户名称:'">
                    </div>
                </div>
                <div style="margin:2px"></div>
                <div class="easyui-panel" id="detailEditToolBar" style="padding:1px;width:100%">
                    <a href="#" id="detailEdit" class="easyui-linkbutton" data-options="onClick:editTable,iconCls:'icon-edit',plain:true">开始</a>
                    <a href="#" id="detailAdd" class="easyui-linkbutton" data-options="onClick:addItem,iconCls:'icon-add',plain:true,disabled:true">增行</a>
                    <a href="#" id="detailDel" class="easyui-linkbutton" data-options="onClick:removeItem,iconCls:'icon-remove',plain:true,disabled:true">删行</a>
                    <a href="#" id="detailCancel" class="easyui-linkbutton" data-options="onClick:resetTable,iconCls:'icon-no',plain:true,disabled:true">取消</a>
                </div>
            
                <div style="margin:2px"></div>
                <table id="orderDetailList" class="easyui-datagrid" style="width:100%;"
                data-options="singleSelect:true,method:'get',onClickRow:setRowIndex,pagination:true,rownumbers:true,onClickCell:setEditingLocation">
                    <thead>
                        <tr>
                            <th data-options="field:'AutoId',hidden:true"></th>
                            <th data-options="field:'Flag',hidden:true"></th>
                            <th data-options="field:'Rate',hidden:true"></th>
                            <th data-options="field:'State',hidden:true"></th>
                            <th data-options="field:'OrderId',hidden:true"></th>
                            <th data-options="field:'ProductionId',width:120,align:'left',formatter:productionFormatter,
                                editor:{type:'combogrid',options:getComboGridInfo(null,'Name',[[
									{field:'AutoId',title:'ID',width:60},
									{field:'Code',title:'代号',width:130},
									{field:'SearchCode',title:'搜索码',width:100},
									{field:'Name',title:'名称',width:150}
								]],productions,productionSelected)}">产品</th>
							<th data-options="field:'ProductionTypeId',hidden:true,width:120,align:'right',hidden:true">类别</th>  							
                            <th data-options="field:'Specification',width:120,align:'left'">规格</th>
                            <th data-options="field:'Quantity1',width:100,align:'left',editor:{type:'numberbox',options:{precision:2,onChange:qtyUpdated}}">销售数量</th>							
                            <th data-options="field:'UnitGroupId',hidden:true,width:100,align:'left',formatter:unitGroupFormatter">单位组</th> 
                            <th data-options="field:'UnitId',width:100,hidden:true,align:'left',formatter:unitFormatter">标准单位</th>           
                            <th data-options="field:'SalesUnitId',width:100,align:'left',formatter:unitFormatter">销售单位</th>
                            <th data-options="field:'Discount',width:100,align:'left',formatter:function(value,row,index){if(value)return value.toFixed(2);else return 0;}">折扣</th>
                            <th data-options="field:'Quantity2',hidden:true,width:100,align:'left',hidden:true">标准单位数量</th>
                            <th data-options="field:'PriceRef0',width:100,align:'left',formatter:moneyFormatter">牌价</th>							
                            <th data-options="field:'Price',width:100,align:'left',formatter:moneyFormatter,editor:{type:'numberbox',options:{precision:2,onChange:priceUpdated,groupSeparator:',',decimalSeparator:'.',prefix:'￥'}}">单价</th>
                            <th data-options="field:'Amount',width:100,align:'left',formatter:moneyFormatter">小计</th>
                            <th data-options="field:'Note',width:100,align:'left',editor:{type:'textbox'}">备注</th>        
                            <th data-options="field:'Define6',width:100,align:'left',formatter:moneyFormatter">牌价金额</th>                            
                            <th data-options="field:'DisAmount',width:100,align:'left',formatter:moneyFormatter">折扣金额</th>
                            <th data-options="field:'DeliveryDate',hidden:true,width:100,align:'left',editor:{type:'datebox',options:{formatter:dateFormatter,parser:dateParser}}">发货日期</th>
                            <th data-options="field:'ProductionName',width:120,align:'left'">品号</th>     
                            <th data-options="field:'BlandId',width:100,align:'left',formatter:blandFormatter">品牌</th>
                            <th data-options="field:'SeriesId',width:100,align:'left',formatter:seriesFormatter">系列</th>
                            <th data-options="field:'Free',width:100,align:'left',formatter:boolFormatter,editor:{type:'checkbox',options:{on:'1',off:'0'}}">赠品</th>
                            <th data-options="field:'Promotion',width:100,align:'left',formatter:boolFormatter">促销品</th>
                            <th data-options="field:'QuoteId',width:100,align:'left',formatter:quoteNameFormatter">适用价格表</th>           
                            <th data-options="field:'PriceRef1',hidden:true,width:100,align:'left'">价格1</th>
                            <th data-options="field:'PriceRef2',hidden:true,width:100,align:'left'">价格2</th>
                            <th data-options="field:'PriceRef3',hidden:true,width:100,align:'left'">价格3</th>
                            <th data-options="field:'PriceRef4',hidden:true,width:100,align:'left'">价格4</th>
                            <th data-options="field:'PriceRef5',hidden:true,width:100,align:'left'">价格5</th>
                        </tr>
                    </thead>
                </table>
                <div id="search" class="easyui-window" title="搜索框" data-options="modal:true,closed:true,iconCls:'icon-save'" style="width:500px;height:450px;padding:10px;">
                <div style="margin-bottom:5px">
                    <input class="easyui-textbox" id="sch_OrderCode" style="width:100%" data-options="label:'单号:'">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-textbox" id="sch_Tel" style="width:100%" data-options="label:'联系电话:'">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-textbox" id="sch_CustomerName" style="width:100%" data-options="label:'客户名称:'">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-textbox" id="sch_DeliveryAddress" style="width:100%" data-options="label:'送货地址:'">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-combobox" id="sch_SalesPointId" style="width:100%" data-options="label:'门店:',valueField:'AutoId',textField:'Name',data:salesPoints">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-combobox" id="sch_SalesId" style="width:100%" data-options="label:'业务员:',valueField:'AutoId',textField:'Name',data:employees">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-combobox" id="sch_DesignerId" style="width:100%" data-options="label:'设计师:',valueField:'AutoId',textField:'Name',data:employees">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-datebox" id="sch_SalesDate1" style="width:100%" data-options="label:'开始时间:',formatter:dateFormatter,parser:dateParser">
                </div>
                <div style="margin-bottom:5px">
                    <input class="easyui-datebox" id="sch_SalesDate2" style="width:100%" data-options="label:'结束时间:',formatter:dateFormatter,parser:dateParser">
                </div>
                <div style="text-align:center;padding:5px 0">
                    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="exeSearch()" style="width:80px">搜索</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearSearch()" style="width:80px">重置</a>
                </div>
                <script>
                function exeSearch() {
                    searchArg = [];
                    var restain1 = {'Key':'OrderCode','Op':'Lk','Value':'%'+$('#sch_OrderCode').textbox('getValue')+'%'};
                    var restain2 = {'Key':'Tel','Op':'Lk','Value':'%'+$('#sch_Tel').textbox('getValue')+'%'};
                    var restain3 = {'Key':'CustomerName','Op':'Lk','Value':'%'+$('#sch_CustomerName').textbox('getValue')+'%'};
                    var restain4 = {'Key':'DeliveryAddress','Op':'Lk','Value':'%'+$('#sch_DeliveryAddress').textbox('getValue')+'%'};
                    searchArg.push(restain1);
                    searchArg.push(restain2);
                    searchArg.push(restain3);
                    searchArg.push(restain4);
                    var sch_sl = $("#sch_SalesId").combobox("getValue");
                    if(sch_sl>0){
                        searchArg.push({'Key':'SalesId','Op':'Eq','Value':sch_sl});
                    }
                    var sch_sp = $("#sch_SalesPointId").combobox("getValue");
                    if(sch_sp>0){
                        searchArg.push({'Key':'SalesPointId','Op':'Eq','Value':sch_sp});
                    }
                    var sch_ds = $("#sch_DesignerId").combobox("getValue");
                    if(sch_ds>0){
                        searchArg.push({'Key':'DesignerId','Op':'Eq','Value':sch_ds});
                    }
                    var sch_dt1 = $("#sch_SalesDate1").datebox("getValue");
                    if(sch_dt1!=''){
                        searchArg.push({'Key':'SalesDate','Op':'Ge','Value':sch_dt1});
                    }
                    var sch_dt2 = $("#sch_SalesDate2").datebox("getValue");
                    if(sch_dt2!=''){
                        searchArg.push({'Key':'SalesDate','Op':'Le','Value':sch_dt2});
                    }
                    $('#search').window('close');
                    setData();
                }
                function clearSearch() {
                    $('#sch_OrderCode').textbox('setValue',"");
                    $('#sch_Tel').textbox('setValue',"");
                    $('#sch_CustomerName').textbox('setValue',"");
                    $('#sch_DeliveryAddress').textbox('setValue',"");
                    $("#sch_SalesId").combobox("setValue","");
                    $("#sch_SalesPointId").combobox("setValue","");
                    $("#sch_DesignerId").combobox("setValue","");
                    $("#sch_SalesDate1").datebox("setValue","");
                    $("#sch_SalesDate2").datebox("setValue","");
                }
             </script>
            </div>
            </div>
        </body>
</html>